/* plain_projection.cpp */

#include <dodo_plot/map/plain_projection.h>
#include <dodo_plot/map/map_utils.h>

namespace dodo_plot
{

Point Plain_Projection::operator() (double lon, double lat) const
{
	switch(current_proj_)
	{
	case 0:
		if(lon > back_center_lon_ && lon <= 180.0)
			return proj_1_(lon, lat);
		else
			return proj_2_(lon, lat);
		break;
	case 1:
		return proj_1_(lon, lat);
		break;
	case 2:
		return proj_2_(lon, lat);
		break;
	}
		
}

Point Plain_Projection::operator() (const Point& lonlat) const
{
	return operator() (lonlat.x, lonlat.y);
}


int Plain_Projection::check_box(double lon_min, double lon_max, double lat_min, double lat_max) const
{
	//TODO add some more judgements?
	//for skipping drawing something...
	if(lon_min < lon_max) // not crossing 180
	{
		if(lon_min <= back_center_lon_ && lon_max >= back_center_lon_)
			return Map_Mode::DOUBLE;
		else
			return Map_Mode::NORMAL;
	}
	else // crossing 180
	{
		if(lon_min <= back_center_lon_ || lon_max >= back_center_lon_)
			return Map_Mode::DOUBLE;
		else
			return Map_Mode::NORMAL;
	}
}

void Plain_Projection::toggle() const
{
	switch(current_proj_)
	{
	case 0:
		current_proj_ = 1;
		break;
	case 1:
		current_proj_ = 2;
		break;
	case 2:
		current_proj_ = 1;
		break;
	}
}

void Plain_Projection::toggle_off() const
{
	current_proj_ = 0;
}

Plain_Projection::Plain_Projection(double lon_min, double lon_max, double lat_min, double lat_max)
	: lon_min_(lon_min), lon_max_(lon_max),
	lat_min_(lat_min), lat_max_(lat_max),
	current_proj_(0)
{
	double lon_span = lon_max - lon_min;
	if(lon_span <= 0)
		lon_span += 360.0;
	double center_lon = in_180(lon_min + lon_span / 2.0);
	back_center_lon_ = in_180(center_lon + 180.0);

	proj_1_ = Pos_Projection(
		Position(0.0, 1.0, 0.0, 1.0),
		Position(lon_min , lon_min + lon_span, lat_max, lat_min)
		);

	proj_2_ = Pos_Projection(
		Position(0.0, 1.0, 0.0, 1.0),
		Position(lon_max - lon_span, lon_max, lat_max, lat_min)
		);

}

}
